var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var expressSession = require("express-session");
var fs = require("fs");
var ejs = require("ejs");
var sass = require("node-sass");
var security = require("./modules/security.js");
var db = require("./modules/db.js");
var sync = require("synchronize");
var User = require("./models/User.js");
var Order = require("./models/Order.js");
require("date-utils");

//settings
app.set("view engine", "ejs");
app.set("views", __dirname + "./views");
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressSession({secret:"lunchbox", resave:true, saveUninitialized:true}));
var scssfile = fs.readFileSync("./views/stylesheets/index.scss", "utf8");
var css = sass.renderSync({ data:scssfile });
app.use(function(req, res, next) { sync.fiber(next) });
app.use(express.static(__dirname + '/public'));
//sync(security, "auth");

//const
var headerPattern = {beforeLogin:1, afterLogin:2, administrator:3};

//routing
app.get("/", function(req, res) {
    res.redirect("/login");
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get('/login', function(req, res) {
  if (security.isAuthenticated(req.session)) {
    res.redirect("/order");
    res.end();
    return;
  }

  //show login form
  res.setHeader("Content-Type", "text/html");
  var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
  var head = fs.readFileSync("./views/header.ejs", "utf8");
  var login = fs.readFileSync("./views/login.ejs", "utf8");
  var r = ejs.render(login, {
    css:css,
    header: ejs.render(head, {pattern:headerPattern.beforeLogin}),
    sidebar: ejs.render(side)
  });
  res.write(r);
  res.end();
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.post("/login", function(req, res) {
  var post = req.body;

  if ( !("id" in post) || !("password" in post)) {
    console.log("invalid parameter!");
    res.redirect("/login");
  } else {

    User.find({id:post.id, password:post.password}, function(e, docs) {
      if (docs.length == 1) {
        console.log("user found.");
        console.log(docs[0].id);
        req.session.auth = true;
        req.session.user = {};
        req.session.user.id = docs[0].id;
        req.session.user.isAdministrator = docs[0].isAdministrator;
        console.log(req.session);
        
        var time = (9 * 60 * 60) + (50 * 60);
        var nowDay = getNowDate(8);
        
        if(!timeOverCheck(time)){
          Order.find({id:req.session.user.id, day:nowDay},function(e , docss){
            console.log("getRecord Count="+docss.length);
            if(docss.length == 0){
              res.redirect("/directOrder");
            }else{
              res.redirect("/order");
            }
          });
        }else{
          res.redirect("/order");
        }
        
      } else {
        console.log("user not found!!!");
        res.redirect("/login");
      }
    });
  }
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/directOrder", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }

  var today = getNowDate(8).substring(6,8)*1;

  //directOrder view
  res.setHeader("Content-Type", "text/html");
  var view = fs.readFileSync("./views/directOrder.ejs", "utf8");
  var r = ejs.render(view, {today:today});
  res.write(r);
  res.end();

});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/order", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }

  //create week array
  var today = new Date();
  var firstday = new Date(today.getFullYear(), today.getMonth(), 1);
  var lastday = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  var current = new Date(today.getFullYear(), today.getMonth(), 1);
  var calendar = [];
  var week = 0;
  var index = 0;
  calendar[week] = [];
  var nowDay;
  var seconds = (today.getHours() * 60 * 60) + (today.getMinutes() * 60) + today.getSeconds();
  var todayOrderFixFlg = 0;

  nowDay = getNowDate(8);
  if (seconds > (9 * 60 * 60) + (50 * 60))
  {
    todayOrderFixFlg = 1;
  }

  for (index=0; index < firstday.getDay(); index++) {
    calendar[week][index] = {"day":0, "outrange":true, "today":false, "holiday":false};
  }
  for (var i=0; i < lastday.getDate(); i++) {
    if (index == 7) {
      week++;
      calendar[week] = [];
      index = 0;
    }
    
    var date;
    date = get8Date(getNowDate(6), current.getDate());

    calendar[week][index] = {"day":current.getDate(), "outrange":false, "today":false, "holiday":false, "date":date, "orderFlg":0};
    if(index == 0 || index == 6 || calendar[week][index].date < nowDay){
      calendar[week][index].orderFlg = 4;
    }else if(calendar[week][index].date == nowDay && todayOrderFixFlg ==1){
      calendar[week][index].orderFlg = 4;
    }else{
      //
    }
    current = new Date(today.getFullYear(), today.getMonth(), current.getDate() + 1);
    index++;
  }
  for (index; index < 7; index++) {
    calendar[week][index] = {"day":0, "outrange":true, "today":false, "holiday":false};
  }

  var strDay;
  var endDay;
  strDay = getNowDate(6) + "01";
  endDay = get8Date(getNowDate(4), (today.getMonth() + 2), 1);

  Order.find({id:req.session.user.id, day:{$gte:strDay, $lt:endDay}},function(e , docss){
    console.log("getRecord Count="+docss.length);

    for (var i=0,leni=docss.length;i<leni;i++) {
      for(var j=0,lenj=calendar.length;j<lenj;j++){
        for(var k=0,lenk=calendar[j].length;k<lenk;k++){

          if(calendar[j][k].orderFlg == 4){
            if(docss[i].day == calendar[j][k].date){
              calendar[j][k].orderFlg = 2;
            }
          }else if(docss[i].day == calendar[j][k].date){

            if(docss[i].day == nowDay){
              if(todayOrderFixFlg == 0){
                calendar[j][k].orderFlg = 1;
              }else{
                calendar[j][k].orderFlg = 2;
              }
            }else if(docss[i].day < nowDay){
              calendar[j][k].orderFlg = 2;
            }else{
              calendar[j][k].orderFlg = 1;
            }
            //console.log("flgOn");
          }else{
          
          }
        }
      }
    }

    //order view
    res.setHeader("Content-Type", "text/html");
    var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
    var head = fs.readFileSync("./views/header.ejs", "utf8");
    var view = fs.readFileSync("./views/order.ejs", "utf8");
    var r = ejs.render(view, {
      css:css,
      header: ejs.render(head, {pattern: (req.session.user.isAdministrator) ? headerPattern.administrator : headerPattern.afterLogin}),
      sidebar: ejs.render(side),
      calendar:calendar
    });
    res.write(r);
    res.end();
  });
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/logout", function(req, res) {
  console.log("logout (session destroyed)");
  security.logout(req.session);
  res.redirect("/login");
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.post("/orderPPP", function(req, res) {

  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }
  var post = req.body;
  var wkDay;
  wkDay = get8Date(getNowDate(6), post.dayToken);

  console.log(post.orderFlg);
  if(post.orderFlg == 0){
    User.find({id:req.session.user.id}, function(e, docs) {
      //console.log(wkDay);
      //console.log(req.session);
      //console.log(docs[0]);
      var o = new Order();
      o.id = req.session.user.id;
      o.day = wkDay;
      o.isFix = false;
      o.user.push(docs[0]);
      o.save();
    });
  }else if(post.orderFlg == 2){
  }else if(post.orderFlg == 4){
  }else{
    Order.find({id:req.session.user.id, day:wkDay},function(e , docss){
      console.log("delete getRecord Count="+docss.length);
      docss[0].remove();
    });
  }
  
  res.redirect("/order");
  res.end();
});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/shopOrder", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }
  if (!req.session.user.isAdministrator) {
    res.redirect("/login");
    res.end();
    return;
  }

  var scssfile2 = fs.readFileSync("./views/stylesheets/shopOrder.scss", "utf8");
  var css2 = sass.renderSync({ data:scssfile2 });
  var nowDay = getNowDate(8);
  //var nowDay = "20141106";

  Order.find({day:nowDay}).populate('user').exec(function(e , docss){
    console.log("getRecord Count="+docss.length);

    var F3 = 0;
    var F4 = 0;
    var F5 = 0;
    var F6 = 0;
    var F7 = 0;
    var F8 = 0;
    var FA = 0;
    var All = 0;
    
    for(var i=0,leni=docss.length;i<leni;i++){
      //console.log(docss[i]);
      if(docss[i].user[0].floor == 3){
        F3++;
      }else if(docss[i].user[0].floor == 4){
        F4++;
      }else if(docss[i].user[0].floor == 5){
        F5++;
      }else if(docss[i].user[0].floor == 6){
        F6++;
      }else if(docss[i].user[0].floor == 7){
        F7++;
      }else if(docss[i].user[0].floor == 8){
        F8++;
      }else{
        FA++;
      }
    }
    All = F3 + F4 + F5 + F6 + F7 + F8;

    console.log("======FA="+FA);
    
    //create orderData array
    var orderData = [];
    orderData[0] = {"floor":3,"Count":F3};
    orderData[1] = {"floor":4,"Count":F4};
    orderData[2] = {"floor":5,"Count":F5};
    orderData[3] = {"floor":6,"Count":F6};
    orderData[4] = {"floor":7,"Count":F7};
    orderData[5] = {"floor":8,"Count":F8};
    
    //shopOrder view
    var sumAmount = amountCanma(All * 450);
    res.setHeader("Content-Type", "text/html");
    var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
    var head = fs.readFileSync("./views/header.ejs", "utf8");
    var sodr = fs.readFileSync("./views/shopOrder.ejs", "utf8");

    var r = ejs.render(sodr, {
      css:css,
      css2:css2,
      header: ejs.render(head, {pattern:headerPattern.administrator}),
      sidebar: ejs.render(side),
      sumAmount:sumAmount,
      orderData:orderData
    });

    res.write(r);
    res.end();
  });

});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/Claim", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }
  if (!req.session.user.isAdministrator) {
    res.redirect("/login");
    res.end();
    return;
  }
  var scssfile2 = fs.readFileSync("./views/stylesheets/shopOrder.scss", "utf8");
  var css2 = sass.renderSync({ data:scssfile2 });
  var nowDay = getNowDate(8);
  //var nowDay = "20141106";

  var strDay = getNowDate(6) + "01";
  var endDay = get8Date(getNowDate(6)*1+1, 1);

  Order.find({day:{$gte:strDay, $lt:endDay}}).sort({id:1}).populate('user').exec(function(e , docss){

    var nowName = "";
    var oldName = "";
    var summaryData = [];
    var cnt = 0;
    for(var i=0,leni=docss.length;i<leni;){
      //console.log(docss[i]);
      var sum = 0;
      nowName = docss[i].user[0].name;
      oldName = docss[i].user[0].name;
      while(nowName == oldName){
        sum += 450;
        i++;
        if(i<leni){
          nowName = docss[i].user[0].name;
        }else{
          break;
        }
      }
      summaryData[cnt] = {};
      summaryData[cnt].name = oldName;
      summaryData[cnt].sum  = sum;
      summaryData[cnt].sumViw = amountCanma(sum);
      cnt++;
      console.log(oldName + ":sum="+sum);
    }
    
    
    //claim view
    res.setHeader("Content-Type", "text/html");
    var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
    var head = fs.readFileSync("./views/header.ejs", "utf8");
    var clim = fs.readFileSync("./views/claim.ejs", "utf8");

    var r = ejs.render(clim, {
      css:css,
      css2:css2,
      header: ejs.render(head, {pattern:headerPattern.administrator}),
      sidebar: ejs.render(side),
      nowDate:getNowDate(8),
      summaryData:summaryData
    });

    res.write(r);
    res.end();
  });

});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/Graph", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }
  if (!req.session.user.isAdministrator) {
    res.redirect("/login");
    res.end();
    return;
  }
  var scssfile2 = fs.readFileSync("./views/stylesheets/shopOrder.scss", "utf8");
  var css2 = sass.renderSync({ data:scssfile2 });
  var nowDay = getNowDate(8);
  //var nowDay = "20141106";

  var strDay = getNowDate(6) + "01";
  var endDay = get8Date(getNowDate(6)*1+1, 1);

  Order.find({day:{$gte:strDay, $lt:endDay}}).sort({id:1}).populate('user').exec(function(e , docss){
    console.log("getRecord Count="+docss.length);
    var nowName = "";
    var oldName = "";
    var summaryData = [];
    var grhData = "";

    grhData = '[["user","amount"]';

    var cnt = 0;
    for(var i=0,leni=docss.length;i<leni;){
      //console.log(docss[i]);
      var grhWk = [];
      var sum = 0;
      nowName = docss[i].user[0].name;
      oldName = docss[i].user[0].name;
      while(nowName == oldName){
        sum += 450;
        i++;
        if(i<leni){
          nowName = docss[i].user[0].name;
        }else{
          break;
        }
      }
      summaryData[cnt] = {};
      summaryData[cnt].name = oldName;
      summaryData[cnt].sum  = sum;
      grhWk = '["'+summaryData[cnt].name +'",'+ summaryData[cnt].sum +']';

      grhData = grhData + "," + grhWk;

      cnt++;
      console.log(oldName + ":sum="+sum);
    }
    grhData = grhData + "]";
    
    //claim view
    res.setHeader("Content-Type", "text/html");
    var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
    var head = fs.readFileSync("./views/header.ejs", "utf8");
    var grah = fs.readFileSync("./views/graph.ejs", "utf8");

    var r = ejs.render(grah, {
      css:css,
      css2:css2,
      header: ejs.render(head, {pattern:headerPattern.administrator}),
      sidebar: ejs.render(side),
      nowDate:getNowDate(8),
      grhData:grhData
    });

    res.write(r);
    res.end();
  });

});
/////////////////////////////////////////////////////////////////////////////////////////////
app.get("/inqOrder", function(req, res) {
  if (!security.isAuthenticated(req.session)) {
    res.redirect("/login");
    res.end();
    return;
  }
//  if (!req.session.user.isAdministrator) {
//    res.redirect("/login");
//    res.end();
//    return;
//  }

  var scssfile2 = fs.readFileSync("./views/stylesheets/shopOrder.scss", "utf8");
  var css2 = sass.renderSync({ data:scssfile2 });

  Order.find({}).sort({id:1,day:1}).populate('user').exec(function(e , docss){

  console.log(docss.length);
    var orderDataAry = [];
    var cnt = 0;
    for(var i=0,leni=docss.length;i<leni;i++){
      //console.log(docss[i]);
      var orderData = [];
      orderData.name = docss[i].user[0].name;
      orderData.id   = docss[i].user[0].id;
      orderData.day  = docss[i].day;

      orderDataAry[cnt] = orderData;
      cnt++;

    }
    
    
    //claim view
    res.setHeader("Content-Type", "text/html");
    var side = fs.readFileSync("./views/sidebar.ejs", "utf8");
    var head = fs.readFileSync("./views/header.ejs", "utf8");
    var clim = fs.readFileSync("./views/inqOrder.ejs", "utf8");

    var r = ejs.render(clim, {
      css:css,
      css2:css2,
      header: ejs.render(head, {pattern:headerPattern.administrator}),
      sidebar: ejs.render(side),
      orderDataAry:orderDataAry
    });

    res.write(r);
    res.end();
  });

});

app.listen(8080);

///////////////////////////////////////////////////////////
// util
///////////////////////////////////////////////////////////
function getNowDate(len){
  var now = new Date();
  var myYear = now.getFullYear();

  var myMonth = now.getMonth() + 1;
  if(myMonth < 10){
    myMonth = "0" + myMonth;
  }

  var myDate = now.getDate();

  if(myDate < 10){
    myDate = "0" + myDate;
  }
  
  var retStr = myYear +""+ myMonth +""+ myDate;
  if(retStr.length > len){
    retStr = retStr.substring(0,len);
  }
  
  return retStr;
}

function get8Date(year, month, day){
  var myYear = year;

  var myMonth = month;
  if(myMonth < 10){
    myMonth = "0" + myMonth;
  }

  var myDate = day;
  if(myDate < 10){
    myDate = "0" + myDate;
  }
  
  var retStr = myYear +""+ myMonth +""+ myDate;
  
  return retStr;
}

function get8Date(yearMonth, day){
  var myYearMonth = yearMonth;

  var myDate = day;
  if(myDate < 10){
    myDate = "0" + myDate;
  }
  
  var retStr = myYearMonth +""+ myDate;
  
  return retStr;
}


function timeOverCheck(secTime){
  var dt = new Date();
  var y= dt.getFullYear();
  var m= dt.getMonth();
  var d= dt.getDate();
  var day=dt.getDay();
  var ret = 0;
  
  var seconds = (dt.getHours() * 60 * 60) + (dt.getMinutes() * 60) + dt.getSeconds();

  if (seconds > secTime){
  	ret = 1;
  }else{
    ret = 0;
  }
  
  return ret;
}

function amountCanma(str){  
  var num = new String(str).replace(/,/g, "");
  while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
  return num;
  
}